package org.ihelpuoo.weboo.upload;

import java.util.HashMap;
import java.util.Map;

import org.ihelpuoo.lang.StringUtils;
import org.ihelpuoo.parser.Inputer;
import org.ihelpuoo.util.Pair;

class FieldHead implements Inputer
{

	private StringBuffer		_sb;
	private Map<String, String>	values;
	private boolean				_isInQuote;
	private boolean				_beforeIsEqual;

	FieldHead()
	{
		values = new HashMap<String, String>();
		resetFlags();
	}

	private void resetFlags()
	{
		_sb = new StringBuffer();
		_isInQuote = false;
		_beforeIsEqual = false;
	}

	public int input(int c)
	{
		if (!_isInQuote && (';' == c || '\n' == c) && _sb.length() > 3) // End of a pair
		{
			// Find current pair seg char is '=' or ':'
			char seg = '=';
			for (int i = 0; i < _sb.length(); i++)
				if (seg == _sb.charAt(i))
					break;
				else if (':' == _sb.charAt(i))
				{
					seg = ':';
					break;
				}
			Pair pair = new Pair();
			pair.setSegChar(seg);
			pair.valueOf(_sb);
			pair.normalize();
			resetFlags();
			if (!StringUtils.isEmpty(pair.getName()))
				values.put(pair.getName(),(String)pair.getValueAsString());
		}
		else if ('\n' == c) // End the head
		{
			if (_sb.length() == 0 || _sb.charAt(0) == '\r')
				return Inputer.DENY;
			else
				return Inputer.ACCEPT;
		}
		else
		{
			_sb.append((char)c);
			if (c == '=')
				_beforeIsEqual = true;
			else if (_beforeIsEqual && c == '"')
			{
				_beforeIsEqual = false;
				_isInQuote = true;
			}
			else if (_isInQuote && c == '"')
			{
				_isInQuote = false;
			}
		}
		return Inputer.ACCEPT;
	}

	String getName()
	{
		return values.get("name");
	}

	String getValue(String name)
	{
		return values.get(name);
	}

	boolean isForFile()
	{
		return values.containsKey("filename");
	}

	boolean isBad()
	{
		return values.size() < 2;
	}

}
